var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.send('<h1>Welcome Realtime Server</h1>');
});

//在线用户
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;

var map_online=new Array();
io.on('connection', function(socket){
    var room_name = '';
    var user_name = '';
    socket.on('in room',function(obj){
        room_name = obj.roomName;
        user_name = obj.userName;
        var functype = obj.functype;
        switch (functype){
            case 'openroom':openroom(socket,obj);
                break;
            case 'joinroom':joinroom(socket,obj);
                break;
            case 'closeroom':closeroom(socket,obj);
                break;
            case 'chatroom':chatroom(socket,obj);
                break;
        }
    });
    socket.on('close',function(obj){
        io.end();
    });
    socket.on('disconnect',function(){
        io.to(room_name).emit('chat message',{"userName":user_name,"msg":user_name+"离开了房间"+room_name});
    })
});

//管理员开房间
function openroom(socket,obj){
    socket.join(obj.roomName);
    map_online[obj.roomName]=[];
    map_online[obj.roomName].push(obj.userName);
    io.to(obj.roomName).emit('chat message',{"userName":obj.userName,"msg":obj.userName+"开通了房间"+obj.roomName});
}

//管理员关房间
function closeroom(socket,obj){
    io.to(obj.roomName).emit('chat message',{"userName":obj.userName,"msg":obj.userName+"关闭了房间"+obj.roomName});
    io.to(obj.roomName).emit('close room',{"status":1});
}


//用户进房间
function joinroom(socket,obj){
    socket.join(obj.roomName);
    map_online[obj.roomName].push(obj.userName);
    io.to(obj.roomName).emit('chat message',{"userName":obj.userName,"msg":obj.userName+"进入了房间"+obj.roomName});
}

//用户发消息
function chatroom(socket,obj){
    io.to(obj.roomName).emit('chat message',{"userName":obj.userName,"msg":obj.msg});
}



http.listen(3000, function(){
    console.log('listening on *:3000');
});